package laji;

import 课设.MyTableModel;
import 课设.User;
import 课设.db;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

public class kaoshi extends JFrame {
    private JTable table;
    private MyTableModel tablemodel;
    private JButton b1;
    private JButton b2;
    private JButton b3;
    private JToolBar tool;

    private JButton b4;
    private JTextField dept;

    public kaoshi() {
        this.setSize(600,300);
        this.setTitle("员工信息");
        this.setLocationRelativeTo(getOwner());//居中

        //获取表格模型(数据),创建组件JTable
        tablemodel = getModel();
        table = new JTable(tablemodel); //table = new JTable(_______);
        table.setPreferredScrollableViewportSize(new Dimension(500,250));
        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add(scroll,BorderLayout.CENTER);

        b1 = new JButton(new ImageIcon("添加"));
        b1.setToolTipText("添加");
        b1.setFocusable(false);
        b1.setHorizontalTextPosition(SwingConstants.CENTER);
        b1.setVerticalTextPosition(SwingConstants.BOTTOM);
        b2 = new JButton();
        b2.setIcon(new ImageIcon("ico\\UPDATE.GIF"));
        b2.setToolTipText("修改");
        b2.setFocusable(false);
        b2.setHorizontalTextPosition(SwingConstants.CENTER);
        b2.setVerticalTextPosition(SwingConstants.BOTTOM);
        b3 = new JButton(new ImageIcon("ico\\DELETE.GIF"));
        b3.setToolTipText("删除");
        b3.setFocusable(false);
        b3.setHorizontalTextPosition(SwingConstants.CENTER);
        b3.setVerticalTextPosition(SwingConstants.BOTTOM);

        //创建工具栏，添加按钮
        tool = new JToolBar();
        tool.add(b1);
        tool.add(b2);
        tool.add(b3);
        tool.setRollover(true);

        //添加工具栏
        getContentPane().add(tool,BorderLayout.NORTH);
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                aaa padd = new aaa();//添加数据
                padd.setVisible(true);
                dispose();
            }
        });
        b2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                int i,index = 0,count;
                db dbcon = new db();
                if(table.getCellEditor() != null) {
                    table.getCellEditor().stopCellEditing();
                }
                try {
                    //
                    String sql = "update users set username = ?,password = ? where userId = ?";
                    //这里更改的时候加上一个notes
                    PreparedStatement presta = dbcon.PreparedStatement(sql);
                    //获得JTable中所修改的行数
                    count = tablemodel.getEditedIndex().size();
                    //获得JTable中所修改的行的数据，更新数据库
                    if(count > 0 ) {
                        for(i=0;i<count;i++) {
                            index = tablemodel.getEditedIndex().get(i);
                            presta.setString(1,(String)table.getValueAt(index, 1));
                            presta.setString(2,(String) table.getValueAt(index, 2));
                            presta.setInt(4,(Integer) table.getValueAt(index, 0));
                            presta.addBatch();
                        }
                    }
                    presta.executeBatch();
                    tablemodel.clearEditedIndex();

                }
                catch(SQLException sqle) {
                    System.out.println(sqle.toString());
                }
            }
        });
        b3.addActionListener(new ActionListener() {//删除
            public void actionPerformed(ActionEvent e) {
                db dbcon = new db();
                try {
                    if(table.getSelectedRows().length>0) {
                        //获得JTable中选中行的序列
                        int[] selRowIndexs = table.getSelectedRows();
                        PreparedStatement presta = dbcon.PreparedStatement("delete from users where userId = ?");
                        for(int i = 0;i<selRowIndexs.length;i++) {
                            //3
                            presta.setString(1, table.getValueAt(selRowIndexs[i],0).toString());//删除无需修改，是按照no来删除的
                            presta.executeUpdate();
                        }

                        //重新加载数据到JTable
                        tablemodel = getModel();
                        table.setModel(tablemodel);
                    }
                }
                catch(SQLException sqle) {
                    System.out.println(sqle.toString());
                }
            }
        });
        b4 = new JButton(new ImageIcon("查询"));
        b4.setToolTipText("查询");
        b4.setFocusable(false);
        b4.setHorizontalTextPosition(SwingConstants.CENTER);
        b4.setVerticalTextPosition(SwingConstants.BOTTOM);

        dept = new JTextField();
        tool.add(b4);
        tool.add(dept);

        b4.addActionListener(new ActionListener() {//查询

            public void actionPerformed(ActionEvent e) {
                db dbcon;
                try{
                    dbcon = new db();
                    String sql = "select * from users where userId = ?";
                    PreparedStatement preparedStatement = dbcon.PreparedStatement(sql);
                    preparedStatement.setString(1,dept.getText());
                    ResultSet rs = preparedStatement.executeQuery();
                    ResultSetMetaData rsmd = rs.getMetaData();
                    int Colnum = rsmd.getColumnCount();
                    tablemodel.setRowCount(0);
                    int i;

                    ArrayList<User> v = new ArrayList<>();
                    while(rs.next()){
                        User user = new User();
                        user.setUserId(rs.getInt("userId"));
                        user.setUsername(rs.getString("username"));
                        user.setPassword(rs.getString("password"));

                        v.add(user);
                    }
                    rs.close();
                    for(i=0;i<v.size();i++){
                        tablemodel.addRow(new Object[]{v.get(i).getUserId(), v.get(i).getUsername(), v.get(i).getPassword()
                        });
                    }
                    dbcon.closeConn();
                }catch (Exception ex){
                    System.out.println(ex.getMessage());
                }
            }
        });
    }

    private MyTableModel getModel() {
        MyTableModel tableModel = new MyTableModel();
        db dbcon;
        try {
            dbcon = new db();
            ResultSet rs = dbcon.executeQuery("select * from users");

            ResultSetMetaData rsmd = rs.getMetaData();//获得查询结果中的列名，填充表格模型列

            int i;
            for (i = 1; i <= rsmd.getColumnCount(); i++)
                tableModel.addColumn(rsmd.getColumnName(i));

            ArrayList<User> v = new ArrayList<>();//获取查询结果中的元组，填充表格模型行
            while (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("userId"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));

                v.add(user);
            }
            rs.close();

            //1
            for (i = 0; i < v.size(); i++) {
                tableModel.addRow(new Object[]{v.get(i).getUserId(), v.get(i).getUsername(), v.get(i).getPassword()});
            }
        } catch (SQLException sqle) {
            System.out.println(sqle);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return tableModel;
    }

    public static void main(String[] args) {
        kaoshi a = new kaoshi();
        a.setVisible(true);
    }
}





